//
//  STCommodityListViewController.swift
//  StarTimesTV
//
//  Created by 胡月明 on 2018/12/29.
//  Copyright © 2018年 StarTimes. All rights reserved.
//

import UIKit
import YYText

//修改section 背景色  为了当right为单数时，颜色统一
extension ListLayoutManager:SectionBgCollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor {
        if let pro : CommodityDataProvider  = listModel as? CommodityDataProvider{
            if(pro.isSeletedAll == false){
                let sections = numberOfSections(in: collectionView)
                if (section == 0||section == sections-1){
                    return UIColor.white
                }
            }
        }
        return UIColor.backViewColor
    }
}

class STCommodityListViewController: STBaseViewController,ListLayoutManagerDelegate,KJSegmentViewDelegate,CommodityDataProviderDelegate {

    override class var routerPagPath:String {
        get {
            return RouterPage.memberProduct.routerPath
        }
    }
    
    var productModel:MemberProductDto = MemberProductDto()
    var channelID:Int?
    var vodID:Int?
    var productId:Int?
    var couponId:Int?
    var selectIndex:Int = 0 { didSet {
        segmentView.normalSelected = selectIndex
    }}
    var unionUTM: String = ""
    
    let commodityDetailCategroy = "STCommodityDetailViewController"
    let commodityListCategroy = "STCommodityListViewController"
    
    private lazy var dataProvider: CommodityDataProvider = {
        let serviec = CommodityDataProvider()
        serviec.statisticCategroy = commodityDetailCategroy
        return serviec
    }()
    
    private lazy var collectViewManager = {
        return ListLayoutManager()
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = SectionBgCollectionViewLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        let view = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 0), collectionViewLayout: layout)
        view.scrollsToTop = true
        view.showsVerticalScrollIndicator = false
        view.backgroundColor = UIColor.backViewColor
        view.alwaysBounceVertical = true
        view.contentInset = UIEdgeInsets(top: scale_width(77), left: 0, bottom: scale_width(92), right: 0)
        return view
    }()
    
    lazy var headerView :CommodityHeaderView2 = {
        let header = CommodityHeaderView2()
        return header
    }()
    
    //nav选择View
    lazy var segmentView :CommoditySegmentView = {
        let segment = CommoditySegmentView(frame: CGRect(x: 0, y:0, width: 208, height: 44))
        segment.backgroundColor = .navigation
        segment.delegate = self
        return segment
    }()
    //segmentView 点击事件
    func selectIndex(_ index: Int) {
        self.collectPageOverStatistics()
        if selectIndex != index {
            
            selectIndex = index

            let isSeletedAll = (index==1)
            
            let isNeedLoad = (dataProvider.allModels.count==0&&isSeletedAll == true)||(dataProvider.singleModel.count==0&&isSeletedAll == false)
            
            if (isNeedLoad) {
                loadData()
            }else{
                reloadListViews(sucessful: true)
            }
        }
    }
    
    private lazy var bottomView: CommoditySportBottomView = {
        let view = CommoditySportBottomView()
        view.isHidden = true
        view.statisticModel = STProductsBuyStatisticModel.init(category: commodityDetailCategroy)
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private lazy var selectButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(resourceName: "ic_checkbox_green_sel"), for: .selected)
        button.setImage(UIImage(resourceName: "ic_checkbox_white"), for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.isSelected = true
        return button
    }()
    
    @objc private func selectedButtonClick(with sinder: UIButton) {
        sinder.isSelected = !sinder.isSelected
    }
    
    private lazy var protocalLabel: YYLabel = {
        let label = YYLabel()
        let string = OLLocalize("agree_with_tos", comment: "") + " " + OLLocalize("public_text_terms_of_service", comment: "")
        let attributedString = NSMutableAttributedString(string: string)
        let range = (string as NSString).range(of: OLLocalize("public_text_terms_of_service", comment: ""))
        attributedString.yy_font = UIFont.regular(with: 12)
        attributedString.yy_color = STColor.olDimGray
        attributedString.yy_setTextUnderline(YYTextDecoration(style: YYTextLineStyle.single, width: 1, color: STColor.olSkyBlue), range: range)
        attributedString.yy_setTextHighlight(range, color: STColor.olSkyBlue, backgroundColor: nil) { (_, _, _, _) in
            STSRouter.openWebpage(.termsOfService)
        }
        label.attributedText = attributedString
        label.numberOfLines = 0
        return label
    }()
    
    lazy var protocalBackView:UIView = {
        let view = UIView()
        return view
    }()
    
    override func loadView() {
        super.loadView()
        self.view.backgroundColor = UIColor.white
        
        self.navigationItem.titleView = segmentView
        view.addSubview(collectionView)
     
        collectionView.addSubview(headerView)
        self.view.addSubview(bottomView)
        self.view.addSubview(protocalBackView)
        
        headerView.frame = CGRect(x: 0, y: -scale_width(77), width: KScreenW, height: scale_width(77))
        
        bottomView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(scale_width(52))
            make.bottom.equalToSuperview().offset(-TabbarSafeBottomMargin())
        }
        
        protocalBackView.snp.makeConstraints { (make) in
            make.leading.trailing.equalTo(view)
            make.height.equalTo(scale_width(40))
            make.bottom.equalTo(bottomView.snp.top)
        }
        protocalBackView.addSubview(selectButton)
        protocalBackView.addSubview(protocalLabel)
        
        protocalBackView.backgroundColor = STColor.olLightGray
        
        selectButton.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(margin4)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(scale_width(40))
        }
        protocalLabel.snp.makeConstraints { (make) in
            make.leading.equalTo(selectButton.snp.trailing)
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().inset(margin12)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.bottom.leading.trailing.equalTo(view)
            make.top.equalTo(topLayoutGuide.snp.bottom)
        }
        
    }
    
    override func className() -> String {
        if selectIndex == 0{
            return commodityDetailCategroy
        }else{
            return commodityListCategroy
        }
    }
    
    override func tvs_rightAction(button: UIButton) {
        STSRouter.openWebpage(.mainFAQ)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        STCountDownTimer.shared.beginTime(target: commodityListCategroy)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        let endTime = STCountDownTimer.shared.endTime(target: commodityListCategroy)
        let event = DSEvent.init(category: commodityListCategroy, action: "pageexit", label: productModel.name, lt: .pv)
        DataStatistics.sendEvent(event: event, msg: ["deal_time":"\(endTime)"])
    }
    
    override func st_deinit() {
        self.dataProvider.cancelAllRequest()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        segmentView.titleArray = []
        segmentView.normalSelected = selectIndex
        navigationItem.rightBarButtonItems = olRightBarButtonItems(title:OLLocalize("action_help"))
        
        // Do any additional setup after loading the view.
        if #available(iOS 11.0, *) {
            self.collectionView.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
        }else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
        registerCell()
        
        collectViewManager.delegate = self
        collectViewManager.listModel = dataProvider

        collectionView.delegate = collectViewManager
        collectionView.dataSource = collectViewManager

        dataProvider.delegate = self

        OTTService.shared.fetchOTTStatus(success: { [weak self] in
            self?.firstRequest()
        }, failure: {_ in})

        NotificationCenter.default.addObserver(self, selector: #selector(ottServiceRightsDidChange), name: .ServiceRightsDidChange, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(loginChangeStatus), name: .UserInfoFinish, object: nil)
        
    }
    
    //登录成功之后
    @objc func loginChangeStatus(){
        self.headerView.updateHeaderViewLoginStatus()
        self.firstRequest()
    }
    
    @objc func ottServiceRightsDidChange() {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: { [weak self] in
            self?.fetchOTTStatus()
        })
    }
    
    func fetchOTTStatus(){
        //todo
        OTTService.shared.fetchOTTStatus(success: { [weak self] in
            self?.updateListContent()
        }) { _ in }

    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: .ServiceRightsDidChange, object: nil)
        NotificationCenter.default.removeObserver(self, name: .UserInfoFinish, object: nil)
        NotificationCenter.default.removeObserver(self)
        self.collectionView.dataSource = nil
        self.collectionView.removeFromSuperview()
    }
    
    func firstRequest(){
        self.view.hud.show()
        
        if unionUTM.count > 0 {
            // 联盟商品
            let id = productId ?? 0
            dataProvider.loadProductData(utm: unionUTM, id: "\(id)")
            return
        }
        else if(channelID != nil) {
            //从直播视频进入
            dataProvider.getProductOfChannel(channelID: channelID!) { [weak self] (model) in
                self?.productModel = model
                self?.dataProvider.loadAllCommodityData()
            }
        }else if (vodID != nil){
            //从点播视频进入
            dataProvider.getProductOfVodId(vodID: vodID!) { [weak self] (model) in
                self?.productModel = model
                self?.dataProvider.loadAllCommodityData()
            }
        }else if (couponId != nil){
            //从优惠券进入
            dataProvider.getProductOfCouponId(couponId: couponId!) { [weak self]  (model) in
                self?.productModel = model
                self?.dataProvider.loadAllCommodityData()
            }
        }
        else {
            //没有参数进商品列表,或者进商品详情
            self.dataProvider.loadAllCommodityData()
        }
    }
    
    func registerCell() {
        //独立内容包
        collectionView.register(SignleCommodityCell.self, forCellWithReuseIdentifier: SignleCommodityCell.sts_reuseIdentifier)
        
        //独立内容包固定期限
        collectionView.register(SignleCommodityTimeCell.self, forCellWithReuseIdentifier: SignleCommodityTimeCell.sts_reuseIdentifier)
        
        //捆绑包
        collectionView.register(CommodityBundledCell.self, forCellWithReuseIdentifier: CommodityBundledCell.sts_reuseIdentifier)
        
        //权益
        collectionView.register(SignleCommodityRightCell.self, forCellWithReuseIdentifier: SignleCommodityRightCell.sts_reuseIdentifier)
        //商品cell  eg:all页面下的商品
        collectionView.register(CommodityAllCell.self, forCellWithReuseIdentifier: CommodityAllCell.sts_reuseIdentifier)
        
        collectionView.register(CollectionBaseHeaderView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier:CollectionBaseHeaderView.sts_reuseIdentifier)
        
        //独立内容包 优惠信息和描述
        collectionView.register(CommodityIntroduceCell.self, forCellWithReuseIdentifier: CommodityIntroduceCell.sts_reuseIdentifier)
    }
    
    func loadData() {
        self.view.hud.hide()
        self.view.hud.show()
        if selectIndex==1 {
            dataProvider.loadAllCommodityData()
        }else{
            dataProvider.reloadData(product: productModel)
        }
    }
    
    
    func reloadListViews(sucessful: Bool) {
        view.hud.hide()
        dataProvider.isSeletedAll = (selectIndex==1)
        updateListContent()
    }
    
    //  因为 ott状态改变导致reloadData 有的时候连续调用后，cell的hidden属性偶尔会变成yes，layoutIfNeeded会在reload结束后再执行下一次reload，并且放在主线程里
    //  CATransaction 是为了去掉reload的时候 闪屏
    func updateListContent() {

        guard collectionView.dataSource != nil else {
            return
        }
        
        DispatchQueue.main.async{
            CATransaction.begin()
            CATransaction.setDisableActions(true)
            self.collectionView.reloadData()
            self.collectionView.layoutIfNeeded()
            self.reloadBottomMoney()
            self.reloadHeader()
            self.collectionView.setContentOffset(CGPoint(x: 0, y: -scale_width(77)), animated: true)
            CATransaction.commit()
        }
    }
    
    public func reloadProducts() {
        firstRequest()
    }
    
    func loadALLListViews(sucessful: Bool) {
        view.hud.hide()

        var arr:[CommodityAllCellModel] = []
        
        for sectionModel in dataProvider.allModels{
            guard let model = sectionModel as? CommodityAllSectionModel else { continue }
            guard (model.rows is [CommodityAllCellModel]) else { continue }
            
            let temp = model.rows as! [CommodityAllCellModel]
            arr = arr + temp
        }
        
        var currenProuctId = self.productModel.id
        
        if productId != nil {
            currenProuctId = productId!
        }
        var isHas = false
        //获取全部的数据后，判断当前商品模型是否存在，不存在获取leve最大的
        for cellmodel in arr{
            if cellmodel.model.id != currenProuctId { continue }
            isHas = true
            self.productModel = cellmodel.model
            break
        }
        
        // 产品ID == 0 or 产品简称nil or 没有找到商品
        if !(productModel.id>0) || (productModel.abbrev_name == nil) || !isHas {
            
            let sortResult = arr.sorted(by: { (a, b) -> Bool in
                return a.model.level > b.model.level
            })
            
            productModel = sortResult.first?.model ?? MemberProductDto()
        }
        
        var count = 0
        for model in dataProvider.allModels{
            if let myModel = model as? CommodityAllSectionModel{
                if (myModel.type == .dataFree || myModel.type == .dataSave){
                    count = count+model.rows.count
                }
            }
        }
        
        if count>1{
            segmentView.titleArray = [productModel.abbrev_name ?? "",OLLocalize("membership_all")] 
        }else if dataProvider.allModels.count == 1{
            selectIndex = 0
            segmentView.titleArray = [productModel.abbrev_name ?? ""]
        }
        
        self.view.hud.show()
        dataProvider.reloadData(product: productModel)
    }
    
    func reloadBottomMoney(){
        var bottomViewHidden = true
        var contentInset = UIEdgeInsets(top: scale_width(77), left: 0, bottom: 0, right: 0)
        if (productModel.product_type == .dataSave && selectIndex==0) {
            bottomViewHidden = false
            contentInset = UIEdgeInsets(top: scale_width(77), left: 0, bottom: scale_width(92), right: 0)
            if productModel.product_type == .dataSave,let arr = dataProvider.commoditysSeciton?.rows{
                for model in arr {
                    
                    if let cellModel = model as? (SignleCommodityCellModel){
                        if cellModel.isSeleted{
                            bottomView.setMemberCommodity(cellModel.model,product:productModel)
                            break
                        }
                    }
                    if let cellModel = model as? (SignleCommodityTimeCellModel){
                        if cellModel.isSeleted{
                            bottomView.setMemberCommodity(cellModel.model,product:productModel)
                            break
                        }
                    }
                }
                
            }
        }
        bottomView.isHidden = bottomViewHidden
        protocalBackView.isHidden = bottomView.isHidden
        collectionView.contentInset = contentInset
    }
    
    func reloadHeader() {
        if selectIndex==1 {
            headerView.reload(productModel: nil)
        }else{
            headerView.reload(productModel: productModel)
        }
    }
    
    func configCell(_ cell: UICollectionViewCell) {
        if let commodityAllCell = cell as? CommodityAllCell {
            commodityAllCell.tapAction = { [weak self] (productModel) in
                guard let strongSelf = self else {
                    return
                }
                
                if strongSelf.selectIndex == 0{
                    DataStatistics.sendEvent(event: DSEvent(category: "CommodityAllCell", action: "ProdTap", label: productModel.name, value: "1", lt: .event))
                }
                
                strongSelf.selectIndex = 0
                strongSelf.segmentView.setNormalType(product: productModel)
                strongSelf.productModel = productModel
                strongSelf.loadData()
            }
        }
        else if let signleCommodityCell = cell as? SignleCommodityCell {
            signleCommodityCell.tapAction = { [weak self] (memberCommodityDto) in
                guard let strongSelf = self else {
                    return
                }
                strongSelf.dataProvider.reloadData(commdity: memberCommodityDto)
                
                var ext = [String:Any]()
                ext[DSKExtension.channel_info.rawValue] = memberCommodityDto.channelInfo
                let event = DSEvent(category: self?.commodityListCategroy ?? "",
                                    action: "commodity_select",
                                    label: memberCommodityDto.name,
                                    value: "1", lt: .event)
                DataStatistics.sendEvent(event: event, msg: ext)
            }
            
        }
        else if let signleCommodityTimeCell = cell as? SignleCommodityTimeCell {
            signleCommodityTimeCell.tapAction = { [weak self] (memberCommodityDto) in
                guard let strongSelf = self else {
                    return
                }
                strongSelf.dataProvider.reloadData(commdity: memberCommodityDto)
            }
        }
        else if let rightCell = cell as? SignleCommodityRightCell {
            rightCell.tapAction = { [weak self] (memberRightsDto) in
                guard let strongSelf = self else {
                    return
                }
                let controller = CommodityRightAlert()
                controller.model = memberRightsDto
                controller.channelArr = strongSelf.productModel.channel_list
                controller.program_list = strongSelf.productModel.program_list
                controller.modalPresentationStyle = .custom
                strongSelf.present(controller, animated: true, completion: nil)
            }
        }
    }

    
    func showReloadAlert() {
        UIHelper.showAlert(title: nil, message: OLLocalize("price_expired"), defaultTitle: OLLocalize("OK"), cancelTitle: "", in: self, defaultAction: { [weak self] in
            self?.dataProvider.allModels = []
            self?.dataProvider.singleModel = []
            self?.collectionView.reloadData()
            self?.firstRequest()
        })
    }
    
    func loadDataUnionProducts(isSuccess: Bool) {
        if isSuccess { return }
        unionUTM = ""
        productModel = MemberProductDto()
    }
}
